import { createRouter, createWebHistory } from 'vue-router'
import main from '../views/main.vue'
import NotFoundView from '../views/404.vue';//404页面组件
import { userInfoStore } from '../store/user.js'
import login from '../views/login.vue'
import demo from '../views/demo.vue'
import demo2 from '../views/demo2.vue'
import demo3 from '../views/demo3.vue'
import index from '../views/index.vue'

const routes = [
    {
        path:'/',
        component:main,
        meta:{
            title:'首页'
        },
        children:[
            {
                path: '',//默认路径
                component: index
            },
            {
                path:'demo',
                name:'demo',
                component:demo,
                meta:{
                    title:'三级菜单测试1'
                }
            },
            {
                path:'demo2',
                name:'demo2',
                component:demo2,
                meta:{
                    title:'三级菜单测试2'
                }
            },
            {
                path:'demo3',
                name:'demo3',
                component:demo3,
                meta:{
                    title:'三级菜单测试3'
                }
            },
        ]
    },
    //其他路由...
    {
        path: '/:pathMatch(.*)*',//捕获所有未匹配的路由
        name: 'not-found',
        component: NotFoundView,
    },
    {
        path:'/login',
        name:'login',
        component:login,
        meta:{
            title:'登录'
        }
    },
];

const router = createRouter({
    history:createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {

    const store = userInfoStore()
    //获取token
    let token = store.token
    //访问的请求不是 login 也没有登录
    if(to.name!=='login'&&!token){
        next({name: 'login'})
    }

    if (to.meta && to.meta.title) {
        document.title = to.meta.title;//浏览器标题设置
    } else {
        document.title = 'OA管理平台';
    }

    if (to.name !== 'not-found' && !router.getRoutes().some(route => route.path === to.path)) {
        next({ name: 'not-found' });//重定向到404页面
    } else {
        next();//正常跳转
    }
});


export default router